import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { View, Image } from '@tarojs/components'

type modeType = 'scaleToFill' | 'aspectFit' | 'aspectFill' | 'widthFix'
| 'heightFix' | 'top' | 'bottom' | 'center' | 'left' | 'right' | 'top left' | 'top right' | 'bottom left' | 'bottom right'

interface Props {
  src: string;
  mode: modeType;
  loadAsBackgroundImage?: boolean;
  opacityTransition?: number;
  onClick?: () => void;
  style?: React.CSSProperties;
  children?: string | JSX.Element;
  lazyLoad?: boolean;
  className?: string;
}

interface ImageITF {
  opacity?: string;
  transition?: string;
}

const imageLoadedStyle = {
  opacity: '1'
};

const ImageFadeIn: React.FC<Props> = ({
  src, loadAsBackgroundImage, opacityTransition, style, children, ...rest
}) => {
  const [loaded, setLoaded] = useState(false)

  const onImageLoad = () => {
    setLoaded(true)
  }

  // add transition style
  const imageStyle: ImageITF = {
    opacity: '0'
  };

  imageStyle.transition = `opacity ${opacityTransition}s ease 0s`;

  return (
    <View>
      {
        !loadAsBackgroundImage ? (
          <Image
            src={src}
            onLoad={onImageLoad}
            {...rest}
            style={loaded ? { ...style, ...imageStyle, ...imageLoadedStyle } : imageStyle}
          />
        ) : (
          <View
            {...rest}
            style={loaded ? { backgroundImage: `url('${src}')`, ...style, ...imageStyle, ...imageLoadedStyle } : imageStyle}
          >
            {children}
          </View>
        )
      }
    </View>
  )
}

export default ImageFadeIn

ImageFadeIn.propTypes = {
  src: PropTypes.string.isRequired,
  loadAsBackgroundImage: PropTypes.bool,
  opacityTransition: PropTypes.number,
  onClick: PropTypes.func,
}

ImageFadeIn.defaultProps = {
  loadAsBackgroundImage: false,
  opacityTransition: 0.5,
}
